package com.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

/**
 * @author: song
 * @data: 2021/9/4 22:01
 */
@Configuration
@Component
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

//    public void addCron(String cron, String orderId) {
//        System.out.println("流程操作 = 动态添加定时任务 = cron = " + cron + "  = orderId = " + orderId);
//        threadPoolTaskScheduler.schedule(() -> clientOrderService.sendSubscribeMessage(orderId),
//                triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
//
//        //数据库 新增定时任务
//        clientCronService.saveCron(cron, orderId);
//    }

    /**
     * 查询数据库 定时任务吧表达式-添加定时任务 避免服务停止后定时任务也停止
     *
     * @param scheduledTaskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//        List<Map<String, Object>> getCronList = clientCronService.getCronList();
//        Optional.ofNullable(getCronList).orElse(new ArrayList<>()).forEach(map -> {
//            System.out.println("查询数据库 = 动态添加定时任务 = map = " + map);
//            scheduledTaskRegistrar.addTriggerTask(
//                    //1.添加任务内容(Runnable)
//                    () -> clientOrderService.sendSubscribeMessage(map.get("orderId").toString()),
//                    //2.设置执行周期(Trigger)
//                    triggerContext -> new CronTrigger(map.get("cron").toString()).nextExecutionTime(triggerContext)
//            );
//        });
    }

}
